<template>
  <section class="todoapp">
    <todo-header @add="handleAdd"></todo-header>
    <todo-main
      @changeAll="handleAll"
      @state="handleState"
      :list="list2"
      @del="handleDel"
    ></todo-main>
    <todo-footer
      @change="
        val => {
          flag = val
        }
      "
      :flag="flag"
      @clear="handleClear"
      :list="list"
    ></todo-footer>
  </section>
</template>

<script>
import TodoHeader from '@/components/TodoHeader.vue'
import TodoMain from '@/components/TodoMain.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components: { TodoHeader, TodoMain, TodoFooter },
  data () {
    return {
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      // 在父组件定义一个数据 后面用来控制样式
      flag: 1
    }
  },
  // 计算属性
  computed: {
    list2 () {
      if (this.flag === 1) {
        return this.list
      } else if (this.flag === 2) {
        return this.list.filter(item => item.isDone === false)
      } else {
        return this.list.filter(item => item.isDone)
      }
    },
    all: {
      get () {
        return this.list.every(item => item.isDone)
      },
      set (val) {
        this.$emit('changeAll', val)
      }
    }
  },
  methods: {
    handleDel (id) {
      // 先找到要删除的条目
      this.list = this.list.filter(item => item.id !== id)
    },
    handleAll (val) {
      // console.log(val);
      this.list.forEach(item => (item.isDone = val))
    },
    handleAdd (todoname) {
      this.list.unshift({
        id: +new Date(),
        name: todoname,
        isDone: false
      })
    },
    handleState (id) {
      // 先找到要修改状态的条目
      const res = this.list.find(item => item.id === id)
      // 修改状态
      res.isDone = !res.isDone
    },
    handleClear () {
      // 找到所有状态为true的删除即可
      this.list = this.list.filter(item => item.isDone === false)
    }
  },
  // 侦听器
  watch: {
    list: {
      deep: true,
      handler: function (newValue) {
        localStorage.setItem('todolist', JSON.stringify(newValue))
      }
    }
  }
}
</script>

<style></style>
